package case_package1;

import java.io.*;
import java.util.Scanner;

public class Login {
    public static void main(String[] args) throws IOException {
        /*
            需求：写一个登录小案例

            步骤：
                将正确的用户名和密码手动保存在本地的userinfo.txt文件中
                保存格式为：username=zhangsan&password=123&count=0
                让用户键盘录入用户名和密码
                        比较用户录入的和正确的用户名密码是否一致
                如果一致则打印登录成功
                    如果不一致则打印登录失败
         */

        //1、读取正确的用户名和密码
        BufferedReader br = new BufferedReader(new FileReader("/Users/zhaoxiaoyong/Documents" +
                "/Java/IO_stream_project/Case_module/src/userinfo.txt"));
        String line = br.readLine();
        br.close();

        // username=zhangsan&password=123&count=0
        String[] userinfo = line.split("&");
        String[] arr1 = userinfo[0].split("=");
        String[] arr2 = userinfo[1].split("=");
        String[] arr3 = userinfo[2].split("=");

        String rightUsername = arr1[1];
        String rightPassword = arr2[1];
        int count = Integer.parseInt(arr3[1]);


        //2、用户键盘录入用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();

        //3、比较
        if (rightUsername.equals(username) && rightPassword.equals(password) && count < 3) {
            System.out.println("登录成功");
        } else {
            count++;
            if (count < 3) {
                System.out.println("登录失败，还剩下" + (3 - count) + "次机会");
            } else {
                System.out.println("用户账户被锁定");
            }

            writeInfo("username=" + rightUsername + "&password=" + rightPassword + "&count=" + count);

        }


    }

    /*
     *   作用：
     *       写出一个字符串到本地文件中
     *   参数：
     *       要写的字符串
     * */
    private static void writeInfo(String content) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/zhaoxiaoyong/Documents/Java" +
                "/IO_stream_project/Case_module/src/userinfo.txt"));

        bw.write(content);
        bw.close();
    }
}
